/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useEffect, useRef, useState } from 'react';
import ProForm, { ProFormRadio, ProFormSelect, ProFormText } from '@ant-design/pro-form';
import { getProductDetail } from '@/services/news/product';
import { PageContainer } from '@ant-design/pro-layout';
import { Button, message, Space, Popconfirm } from 'antd';
import { useLocation } from 'umi';
import KbFormTag from '@/components/_pages/news/product/components/KbFormTag';
import KbBraftEditor from '@/components/KbBraftEditor/index';
import KbPreviewModal from '@/components/_pages/news/product/components/KbPreviewModal';
import { addTag, delTag, getTagList, essayEdit } from '@/services/news/product';
import { history } from 'umi';
import type { Location } from 'umi';
import type { ProFormInstance } from '@ant-design/pro-form';
import type { PublishItem } from '@/components/_pages/news/product/utils';
import { productType, topStatus } from '@/components/_pages/news/product/utils';

const Index = () => {
  const formRef = useRef<ProFormInstance>();
  const [dTags, setDTags] = useState<string[]>([]);
  const [tags, setTags] = useState<string[]>([]);
  const [addTags, setAddTags] = useState<string[]>([]);
  const [deleteTags, setDtteleTags] = useState<string[]>([]);
  const [tagStatus, setTagStatus] = useState<boolean>(false);
  const { query: urlParams } = useLocation() as Location;
  const { id = '' }: any = urlParams;
  const [visible, setVisible] = useState<boolean>(false);
  const [dataSource, setDataSource] = useState<PublishItem | any>();

  const checkFormData = () => {
    return new Promise<PublishItem>((resolve) => {
      formRef.current?.validateFields().then((res) => {
        const { content, ...rest } = res;
        resolve({ content: content.toHTML(), ...rest });
      });
    });
  };
  const handleOpenPreViewModal = () => {
    checkFormData().then((res) => {
      setDataSource(res);
      setVisible(true);
    });
  };
  const handleClosePreViewModal = () => {
    setDataSource(undefined);
    setVisible(false);
  };
  const getTagData = async () => {
    const { data: tagList } = await getTagList();
    setTags(tagList);
    setDTags(tagList);
  };
  const handleChange = () => {};
  const handleDeleteTags = (tag: string) => {
    setDtteleTags([...deleteTags, tag]);
  };
  const handleaddTags = (tag: string) => {
    setAddTags([...addTags, tag]);
  };
  const handleTagsStatus = () => setTagStatus(!tagStatus);
  const handleTagsCancel = () => {
    setTags(dTags);
    handleTagsStatus();
  };
  const handleBack = () => {
    history.goBack();
  };
  const handleSaveTags = () => {
    handleTagsStatus();
    const promiseList = [];
    if (addTags.length > 0) {
      promiseList.push(addTag({ tag: addTags }));
    }
    if (deleteTags.length > 0) {
      promiseList.push(delTag({ tag_name: deleteTags }));
    }
    Promise.all(promiseList).then((res) => {
      const reject = res.filter((item) => item.code > 0);
      if (reject.length > 0) {
        message.error(reject[0].msg);
      } else {
        message.success('编辑标签成功');
      }
      setAddTags([]);
      setDtteleTags([]);
      getTagData();
    });
  };

  const handleFinish = async (type: string) => {
    checkFormData().then((response) => {
      essayEdit({ ...response, status: type, id }).then((res) => {
        const { code, msg } = res;
        if (code == 0) {
          message.success('操作成功');
          handleBack();
        } else {
          message.error(msg);
        }
      });
    });
  };

  useEffect(() => {
    getTagData();
    if (id) {
      getProductDetail({ id }).then((res) => {
        const { data } = res;
        formRef.current?.setFieldsValue(data);
      });
    }
  }, [urlParams]);
  return (
    <PageContainer>
      <h1>发布文章</h1>
      <ProForm
        formRef={formRef}
        wrapperCol={{ span: 6 }}
        submitter={{
          render: () => [
            <Popconfirm
              title='确定发布内容？'
              key='publish'
              onConfirm={handleFinish.bind(null, '1')}
            >
              <Button type='primary'>发布</Button>
            </Popconfirm>,
            <Popconfirm
              title='将编辑内容存入草稿箱？'
              key='drafts'
              onConfirm={handleFinish.bind(null, '0')}
            >
              <Button type='primary'>存草稿</Button>
            </Popconfirm>,
            <Button key='preview' type='primary' onClick={handleOpenPreViewModal}>
              预览
            </Button>,
            <Popconfirm title='确认放弃编辑？' key='cancel' onConfirm={handleBack}>
              <Button type='primary' ghost>
                取消
              </Button>
            </Popconfirm>,
          ],
        }}
        initialValues={{
          top: '0',
        }}
      >
        <ProFormText
          label='标题'
          name='title'
          rules={[{ required: true, message: '请输入文章标题' }]}
        />
        <ProFormSelect
          label='分类'
          name='category'
          valueEnum={productType}
          rules={[{ required: true, message: '请选择类别' }]}
        />
        <ProForm.Item label='内容' name='content' wrapperCol={{ span: 18 }}>
          <KbBraftEditor onChange={handleChange} />
        </ProForm.Item>
        <ProForm.Item
          label='标签'
          name='tag'
          wrapperCol={{ span: 18 }}
          rules={[
            {
              validator: (_, value) =>
                value.length > 5 ? Promise.reject(new Error('标签最多选择5个')) : Promise.resolve(),
            },
          ]}
        >
          <KbFormTag
            description={tags}
            status={tagStatus}
            onChange={handleChange}
            onTags={setTags}
            onAddTags={handleaddTags}
            onDeleteTags={handleDeleteTags}
          />
        </ProForm.Item>
        <ProForm.Item>
          {tagStatus ? (
            <Space>
              <Button type='primary' onClick={handleSaveTags}>
                保存标签
              </Button>
              <Button onClick={handleTagsCancel}>取消</Button>
            </Space>
          ) : (
            <Button type='primary' onClick={handleTagsStatus}>
              编辑标签
            </Button>
          )}
        </ProForm.Item>
        <ProFormRadio.Group label='置顶' name='top' valueEnum={topStatus} />
      </ProForm>
      <KbPreviewModal content={dataSource} visible={visible} onCancel={handleClosePreViewModal} />
    </PageContainer>
  );
};

export default Index;
